package com.fy.fyspace.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class ThreadPoolConfig {

  @Bean
  public ThreadPoolTaskExecutor imageProcessThreadPool() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(5); // 核心线程数
    executor.setMaxPoolSize(10); // 最大线程数
    executor.setQueueCapacity(100); // 队列容量
    executor.setKeepAliveSeconds(60); // 线程空闲时间
    executor.setThreadNamePrefix("image-process-"); // 线程名前缀
    // 拒绝策略：调用者运行
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor;
  }

  /**
   * AI任务处理线程池
   */
  @Bean("aiTaskThreadPool")
  public ThreadPoolExecutor aiTaskThreadPool() {
    return new ThreadPoolExecutor(
            5,                      // 核心线程数
            10,                    // 最大线程数
            60L,                   // 空闲线程存活时间
            TimeUnit.SECONDS,      // 时间单位
            new LinkedBlockingQueue<>(100),  // 任务队列
            new ThreadPoolExecutor.CallerRunsPolicy()  // 拒绝策略
    );
  }

  /**
   * 批量操作线程池 - 专门用于批量收藏、取消收藏等操作
   */
  @Bean("batchOperationThreadPool")
  public ThreadPoolExecutor batchOperationThreadPool() {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(
            3,                      // 核心线程数 - 较小，避免数据库连接过多
            8,                     // 最大线程数
            60L,                   // 空闲线程存活时间
            TimeUnit.SECONDS,      // 时间单位
            new LinkedBlockingQueue<>(50),   // 任务队列 - 适中大小
            new ThreadPoolExecutor.CallerRunsPolicy()  // 拒绝策略 - 调用者运行，确保任务不丢失
    );
    
    // 添加线程池监控日志
    log.info("批量操作线程池初始化完成 - 核心线程数：{}，最大线程数：{}，队列容量：{}", 
             executor.getCorePoolSize(), executor.getMaximumPoolSize(), executor.getQueue().remainingCapacity());
    
    return executor;
  }

  /**
   * 获取线程池状态信息
   */
  public static String getThreadPoolStatus(ThreadPoolExecutor executor, String poolName) {
    if (executor == null) {
      return poolName + " - 线程池未初始化";
    }
    
    return String.format("%s - 活跃线程：%d，核心线程：%d，最大线程：%d，队列大小：%d，已完成任务：%d",
            poolName,
            executor.getActiveCount(),
            executor.getCorePoolSize(),
            executor.getMaximumPoolSize(),
            executor.getQueue().size(),
            executor.getCompletedTaskCount());
  }
}